package org.nokatag.common;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * html字符提取
 * @author rebin
 *
 */
public class HtmlToText {
	private static final String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // 定义script的正则表达式  
    private static final String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // 定义style的正则表达式  
    private static final String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式  
    private static final String regEx_space = "\\s*|\t|\r|\n";//定义空格回车换行符  
      
    /** 
     * @param htmlStr 
     * @return 
     *  删除Html标签 
     */  
    private static String delHTMLTag(String htmlStr) {  
        Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);  
        Matcher m_script = p_script.matcher(htmlStr);  
        htmlStr = m_script.replaceAll(""); // 过滤script标签  
        Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);  
        Matcher m_style = p_style.matcher(htmlStr);  
        htmlStr = m_style.replaceAll(""); // 过滤style标签  
  
        Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);  
        Matcher m_html = p_html.matcher(htmlStr);  
        htmlStr = m_html.replaceAll(""); // 过滤html标签  
  
        Pattern p_space = Pattern.compile(regEx_space, Pattern.CASE_INSENSITIVE);  
        Matcher m_space = p_space.matcher(htmlStr);  
        htmlStr = m_space.replaceAll(""); // 过滤空格回车标签  
        return htmlStr.trim(); // 返回文本字符串  
    }  
      
    public static String getTextFromHtml(String htmlStr){  
        htmlStr = delHTMLTag(htmlStr);  
        htmlStr = htmlStr.replaceAll(" ", "");  
        return htmlStr;  
    }
    
    /**
     * 截取html子串
     * @param htmlStr
     * @param len
     * @return
     */
    public static String subFromHtml(String htmlStr,int start,int len){
    	if(null==htmlStr || htmlStr.trim().length()<1)
    		return null;
    	String hstr = getTextFromHtml(htmlStr.replace("\\r", "").replace("\\n",""));
    	if(len>=hstr.length())
    		return hstr;
    	String gs =hstr.substring(start,start+len);//&nbsp;s
		int maxF = 0;//最后一个&符号位置
		int indx = 0;
		for(String k:gs.split("")){
			if("&".equals(k))
				maxF=indx;
			indx++;
		}
		if(maxF>0 && gs.substring(maxF,gs.length()).indexOf(";")==-1){
			String ks = hstr.substring(gs.length(),hstr.length());
			gs+=ks.substring(0,ks.indexOf(";")+1);
		}
		return gs;
    }
}
